import React, { useState, useCallback } from 'react';
import { List } from 'react-vant'
import { Toast } from 'antd-mobile'
import HeadTop from '@/components/HeadTop';
import ListItem from '@/components/ListItem';
import Loading from '@/components/Loading';
import { listFields } from '../_parts/const';
import ApiIndex from '@/api/spotCheck';
import './index.less'

import { MyContext } from '@/context/index';
const { Provider } = MyContext

const Index = ({ history }) => {
    const [inputVal, setInputVal] = useState('');
    const [list, setList] = useState([]);
    const [loading, setLoading] = useState(false);
    const [finished, setFinished] = useState(false);
    const [pageIndex, setPageIndex] = useState(1);

    const getList = async (value = '',search) => {
        setLoading(true);
        if (loading) return
        let params = {
            page: search ? 1 : pageIndex,
            size: 10000,
            type: 'PATROL_INSPECTION',
            statusList: ['WAIT_FINISH', 'PROCESSING'],
            deviceCode: value || ''
        }
        try {
            // let res = await ApiIndex.getList(params);
            let res = null
            if (value) {
                res = await ApiIndex.searchKey(params)
            } else {
                res = await ApiIndex.getList(params);
            }

            setLoading(false);

            if (res.data.code == 0) {
                let _data = res.data.data.records
                if (search == 'search') {
                    setList(_data);
                    setFinished(true);
                } else {
                    setList((prevList) => [...prevList, ..._data]);
                }
                // 判断是否还有更多数据
                if (_data.length < 10) {
                    setFinished(true);
                } else {
                    setPageIndex((prevIndex) => prevIndex + 1);
                }
            } else {
                setFinished(true);
            }
        } catch (error) {
            console.error('Error:', error);
            setLoading(false);
            setFinished(true);
        }
    };

    const loadMoreData = () => {
        setPageIndex((prevIndex) => prevIndex + 1);
        getList();
    };

    // 搜索
    const getHeadTopSearch = useCallback((value) => {
        setPageIndex(1)
        setInputVal(value)
        let _value = value
        if (value.indexOf("*") != -1) {
            _value = value.split("*")[0]
        }

        getList(_value, 'search')

        return
        setInputVal(value)
        if (value) {
            let _value = value
            if (value.indexOf("*") != -1) {
                _value = value.split("*")[0]
            }
            let arr = list.filter(el => el.no == _value)
            if (!arr.length) {
                setList([])
                Toast.show({
                    content: '暂无匹配数据'
                })
                return
            }
            arr.length && setList([...arr])
        }else{
            getList('search')
        }


    }, [inputVal])

    return (
        <div className='page-wrapper'>
            {
                loading ? <Loading></Loading> : null
            }
            <Provider value={{ placeholderTxt: "请输入巡检编号", inputVal: inputVal }}>
                <HeadTop
                    title="设备巡检"
                    rightTxt="巡检记录"
                    history={history}
                    getHandleRight={() => history.push("/inspectionRecord")}
                    search={true}
                    sendHandlePressVal={getHeadTopSearch}
                ></HeadTop>
            </Provider>
            <div className="page-body" style={{ padding: 15 }}>
                <List finished={finished} errorText='请求失败，点击重新加载' onLoad={getList}>
                    {
                        list.map(el => <ListItem
                            key={el.id}
                            item={el}
                            history={history}
                            detailUrl="/inspectionDetail"
                            listFields={listFields}
                        ></ListItem>)
                    }
                    {finished ? <div className='loadingTxt'>无更多数据</div> : null}
                </List>
                {!loading && !finished && (
                    <div style={{ textAlign: 'center', padding: '10px', marginBottom: '10px' }}>
                        <span onClick={loadMoreData}>Load More</span>
                    </div>
                )}
            </div>
        </div>
    );
}

export default Index;
